/*
* @Author: liTengZhen
* @Date:   2017-06-30 11:43:51
*/
var BuyCart={

    key : 'o2oShop'+$('#uId').val(),
    sId : $('#sId').val(),
    delIte: '',

    /**
     * 初始化结算价格、购物车数量
     */
    initCart: function(){
        var car = localStorage.getItem(this.key);

        var init={
                'price' : 0,
                'number': 0
        };
        //console.log(car);
        //localStorage.removeItem(this.key);
        if( car ){
          car = JSON.parse(car);
          var type = typeof(car[this.sId]);
          if( type != "undefined" ){
            car = car[this.sId];
            for(var i in car){
                init['price']+=car[i]['goodsPri']*car[i]['goodsNum'];
                init['number']+=parseInt(car[i]['goodsNum']);
            }
          }
        }

        //console.log(init);
        return init;
    },


    /**
     * 购物车商品
     * @return 购物车商品
     */
    cartInfo: function(){
        var car = localStorage.getItem(this.key);

        if(car){
          car = JSON.parse(car);
          var type = typeof(car[this.sId]);
          if( type != "undefined"){
            car = car[this.sId];
          }else{
            car = false;
          }
        }
        return car;
    },


    /**
     * 点击添加按钮
     * @param obj obj [description]
     * @param int 1:点击购物车中的按钮添加到购物车 2:点击商品列表中的添加按钮
     */
    addToCart: function(obj,type){
      var info         = $(obj).data('info');
      var gId          = info['goodsId'];


      var data = {
        'goodsId' : gId,
        'gcount'  : 1,
        'goodsAttrId' : info['goodsAttrId'] || 0,
      };
      //点击商品列表
      if(type == 2){

        this.addCart(data, obj);
      }else if(type == 1){ //点击购物车

        this.sendAddToCart(data);
      }


    },


    /**
     * 商品详情添加到购物车
     * @param obj obj [description]
     */
    addToCart1: function(obj,num,isGroup,isSeckill,shopId){
        // console.log(obj);
        // console.log($(obj).data('info'));
      var info         = $(obj).data('info');
      var gId          = info['goodsId'];

      var data = {
        'goodsId' : gId,
        'gcount'  : num,
        'goodsAttrId' : info['id'] || 0,
        'isGroup':isGroup,
        'isSeckill':isSeckill,
        'shopId':shopId
      };
      this.sendAddToCart(data);

    },


    /**
     * 点击减少按钮
     * @param obj obj [description]
     * @param int 1:点击购物车中的按钮减少到购物车 2:点击商品列表中的减少按钮
     */
    delFromCart: function(obj, type){
      var info         = $(obj).data('info');
      var gId          = info['goodsId'];
      var num = $(obj).val();
      if(num==0){
        var gattrId = 0;
        if(typeof(info['id']) !='undefined'){
          gattrId = info['id'];
        }

        if(typeof(info['goodsAttrId']) !='undefined'){
          gattrId = info['goodsAttrId'];
        }

        var data={
          ids : gId+'_'+gattrId+'_0_0'
        };


        this.sendDelCart(data, type , obj);

      }else{

        var data={
          goodsId : gId,
          num     : num,
        };


        if(typeof(info['goodsAttrId']) !='undefined'){
          data['goodsAttrId'] = info['goodsAttrId'];
        }
        this.changeCartGoodsNum(data, type);
      }

    },

    /**
     * 点击商品列表中的商品添加购物车商品请求
     */
    addCart: function(data,obj){

      $.post('/Wx/Cart/addCart', data, function(res){
          if(data.isGroup==1 || data.isSeckill==1){
              if(res['status']<0){
                  mui.toast(res['msg']);
              }else{
                  var type = data.isSeckill==1?'isSeckill':'isGroup';
                  location.href="/wx/Confirm/conFirmOrder/shopId/"+data.shopId+"/goodsId/"+data.goodsId+"/"+type+"/1";
              }

          }else{

              if(res['status']<0){
                  mui.toast(res['msg']);
                  return false;
              }

              var gId = $(obj).data('info')['goodsId'];
              var flag = 0;
              $('.gwc-ttab').each(function(i, n){
                //更改购物车中商品的数量
                if($(n).data('id') == gId){
                    flag = 1;
                    var $el  = $(n).find('.v-jg');
                    var temp = parseInt($el.val()) + 1;
                    $el.val(temp);
                    return false;
                }
              })

              //购物车中无此商品,需新增一列
              if(flag == 0){
                var $goodsInfo = $(obj).closest('.main-goods-section-r-lb');
                $obj = $(obj).closest('.sfq'); //刷新数量容器

                var html = '';
                    html+='<div data-id="'+gId+'" class="gwc-ttab">';
                    html+='     <div class="jd">'+$goodsInfo.find('.yichu').html()+'</div>';
                    html+='     <div class="jd-m dj">'+$goodsInfo.find('.dj').html()+'</div>';
                    html+='         <div class="sfq">';
                    html+='             <div class="jian" style="display: block;">-</div>';
                    html+='             <input class="v-jg" readonly unselectable="on" disabled data-info=\''+JSON.stringify($(obj).data('info'))+'\' type="number" max="999" value="1">';
                    html+='             <div class="jia">+</div> ';
                    html+='         </div>';
                    html+='</div>';
                $('#carGoods').append(html);
              }

              mui.toast('成功添加');


          }

        })

    },

    /**
     * 添加购物车商品请求
     */
    sendAddToCart: function(data){

      $.post('/Wx/Cart/addCart', data, function(res){
          if(data.isGroup==1 || data.isSeckill==1){
              if(res['status']<0){
                  mui.toast(res['msg']);
              }else{
                  var type = data.isSeckill==1?'isSeckill':'isGroup';
                  location.href="/wx/Confirm/conFirmOrder/shopId/"+data.shopId+"/goodsId/"+data.goodsId+"/"+type+"/1";
              }

          }else{

              if(res['status']<0){
                  mui.toast(res['msg']);
                  return false;
              }
              //没有多种规格的商品才需要让商品列表中对应的商品数量加一
              if(data['goodsAttrId']==0){
                var $carList = $('.main-goods-section-r').find('.v-jg');
                //商品列表中的对应商品的数量也应加一
                $carList.each(function(i, n){
                  if( $(n).data('info')['goodsId'] == data['goodsId'] ){
                      $(n).val($(n).val()*1+1);
                      return false;
                  }
                })
              }
              mui.toast('成功添加');

          }

        })

    },




    /**
     * 删除购物车商品请求
     * @param json [data] [发送的参数]
     * @param int type 1:无操作 2:点击购物车中的商品，需删除
     */
    sendDelCart: function(data, type, obj){
      $.post('/Wx/Orders/delCartGoods', data, function(result){
          if(result['status']==-1){
            mui.toast('操作失败');
            return false;
          }
          var gid = data['ids'].split('_')[0];

          if(type==1){
            $(obj).closest('.gwc-ttab').remove();
            $('.v-jg').each(function(i, n){
                if( $(n).data('info')['goodsId'] == gid ){

                    $(n).val($(n).val()*1-1);
                    if(parseInt($(n).val()) == 0){
                        $(n).prev().css('display', 'none');
                        $(n).val('');
                    }
                    return false;
                }
            })
          }else if(type == 2){

            $('.gwc-ttab').each(function(i, n){
                //console.log(gid);
                if($(n).data('id') == gid){
                    $(n).closest('.gwc-ttab').remove();
                    return false;
                }
            })
          }

          mui.toast('成功删除该商品');
        })
    },

    /**
     * 修改购物车商品数量请求
     */
    changeCartGoodsNum: function(data, type){
      $.post('/Wx/Cart/changeCartGoodsNum', data, function(result){
          if(result['status']==-1){
            mui.toast('操作失败');
            return false;
          }

            //点击购物车商品减号,商品列表中的对应商品的数量也应减一
            if(type ==1){
                var $carList = $('.main-goods-section-r').find('.v-jg');
                $carList.each(function(i, n){
                    if( $(n).data('info')['goodsId'] == data['goodsId'] ){
                        $(n).val($(n).val()*1-1);
                        return false;
                    }
                })
            }else if( type ==2){ //点击商品列表减号
                $('.gwc-ttab').each(function(i, n){
                    //更改购物车中商品的数量
                    if($(n).data('id') == data['goodsId']){
                        var $el  = $(n).find('.v-jg');
                        var temp = parseInt($el.val()) - 1;
                        $el.val(temp);
                        return false;
                    }
                })

            }

        })
    },

    /**
     * 清空购物车
     */
    destroyCart: function(){
      var data={
        uid: $('#uId').val(),
        sid: $('#sId').val(),
      };
      $.post('/Wx/Cart/destroyCart', data, function(data){
          if(data['status']<0){
            mui.toast('操作失败');
            return false;
          }else if(data['status'] == 1){
            mui.toast('操作成功');
            $('#carGoods').html('');
            $('.gwc-tan').stop().slideToggle();
            $('.zhezhao').toggleClass('zhezhao-active');
            $('.gwc-circle').html(0);
            $('.js-jg').html('¥0');
          }
          //mui.toast('成功删除该商品');
        })
    },

    /**
     * 检测对象是否为空
     * @param  {[type]}  obj [description]
     * @return Boolean
     */
    isEmpty: function(obj){
        for(var i in obj){
            return false;
        }
        return true;
    }
}


